﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace WpfCropImage
{
    public static class ImageHelper
    {

        /// <summary>
        /// 自动去除图片左右色边
        /// </summary>
        /// <param name="filename">文件路径</param>
        /// <param name="color">要去除的色边颜色</param>
        /// <param name="yscale1">开始位置比例，上至下，从哪个比例开始（0.25就代表从图片25%处开始检测）</param>
        /// <param name="yscale2">结束位置比例，上至下，到哪个位置结束（0.5就代表检测到50%为止）</param>
        /// <returns></returns>
        public static Bitmap AutoCutColorEdge2(Bitmap bmp, Color color, double yscale1, double yscale2)
        {
           
            Color c = new Color();
            int max_Left = bmp.Width / 2, min_Right = bmp.Width / 2;
            for (int y = Convert.ToInt32(bmp.Height * yscale1); y < bmp.Height * yscale2; y++)//b.Height  
            {
                for (int x = bmp.Width / 2; x >= 0; x--)//找到最靠左的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (max_Left > x)
                        {
                            max_Left = x;
                        }
                    }
                }
                for (int x = bmp.Width / 2; x < bmp.Width; x++)//找到最靠右的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (min_Right < x)
                        {
                            min_Right = x;
                        }
                    }
                }
            }
            //最左边黑边：903，最右边黑边：1475
            //Console.WriteLine($"最左邊黑邊：{max_Left}，最右邊黑邊：{min_Right}");
            //创建一个画框：宽（右黑边起始位置-左黑边最终位置=去除黑边之后的宽度），高（整个图片 的图框）
            Bitmap huakuang = new Bitmap(min_Right - max_Left, bmp.Height);//2162 - 239 =1923
            //创建一个画布：宽高和画框一致
            Graphics huabu = Graphics.FromImage(huakuang);
            //清空画布（透明）
            huabu.Clear(System.Drawing.Color.Transparent);
            //画布上所要画的位置和大小
            RectangleF huabu_rec = new RectangleF(0, 0, min_Right - max_Left, bmp.Height);
            //图片所要裁剪矩形的大小和位置：
            //x=intLeft（从左黑边最终位置开始），y=0
            //width=intRight - intLeft（右黑边起始位置-左黑边最终位置=去除黑边之后的宽度），height=整个图片的高
            RectangleF img_rec = new RectangleF(max_Left, 0, min_Right - max_Left, bmp.Height);
            //在画布上的指定位置大小(huabu_rec)画上图片(bmp)的指定部分(img_rec)
            huabu.DrawImage(bmp, huabu_rec, img_rec, GraphicsUnit.Pixel);
            bmp.Dispose();
            huabu.Dispose();
            return huakuang;
        }
        /// <summary>
        /// 自动去除图片上下色边
        /// </summary>
        /// <param name="filename">文件路径</param>
        /// <param name="color">要去除的色边颜色</param>
        /// <param name="xscale1">开始位置比例，上至下，从哪个比例开始（0.25就代表从图片25%处开始检测）</param>
        /// <param name="xscale2">结束位置比例，上至下，到哪个位置结束（0.5就代表检测到50%为止）</param>
        /// <returns></returns>
        public static Bitmap AutoCutColorEdge3(Bitmap bmp, Color color, double xscale1, double xscale2)
        {
            Color c = new Color();
            int min_Top = bmp.Height / 2, max_Bottom = bmp.Height / 2;
            for (int x = Convert.ToInt32(bmp.Width * xscale1); x < bmp.Width * xscale2; x++)//b.Height  
            {
                for (int y = bmp.Height / 2; y >= 0; y--)//找到最靠左的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (min_Top > y)
                        {
                            min_Top = y;
                        }
                    }
                }
                for (int y = bmp.Height / 2; y < bmp.Height; y++)//找到最靠右的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (max_Bottom < y)
                        {
                            max_Bottom = y;
                        }

                    }
                }
            }
            //最上边黑边：140，最下边黑边：986
            //Console.WriteLine($"最上边黑边：{min_Top}，最下边黑边：{max_Bottom}");
            //创建一个画框：宽
            Bitmap huakuang = new Bitmap(bmp.Width, max_Bottom - min_Top);//986 - 140 =846
            //创建一个画布：宽高和画框一致
            Graphics huabu = Graphics.FromImage(huakuang);
            //清空画布（透明）
            huabu.Clear(System.Drawing.Color.Transparent);
            //画布上所要画的位置和大小
            RectangleF huabu_rec = new RectangleF(0, 0, bmp.Width, max_Bottom - min_Top);
            //图片所要裁剪矩形的大小和位置：
            RectangleF img_rec = new RectangleF(0, min_Top, bmp.Width, max_Bottom - min_Top);
            //在画布上的指定位置大小(huabu_rec)画上图片(bmp)的指定部分(img_rec)
            huabu.DrawImage(bmp, huabu_rec, img_rec, GraphicsUnit.Pixel);
            bmp.Dispose();
            huabu.Dispose();
            return huakuang;
        }
        /// <summary>
        /// 自动去除图片上下色边
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <param name="color">要去除的色边颜色</param>
        /// <param name="xscale1">开始位置比例，上至下，从哪个比例开始（0.25就代表从图片25%处开始检测）</param>
        /// <param name="xscale2">结束位置比例，上至下，到哪个位置结束（0.5就代表检测到50%为止）</param>
        /// <returns></returns>
        public static Bitmap AutoCutColorEdge4(Bitmap bmp, Color color, double xscale1, double xscale2)
        {
            Color c = new Color();
            int min_Top = bmp.Height / 2, max_Bottom = bmp.Height / 2;
            for (int x = Convert.ToInt32(bmp.Width * xscale1); x < bmp.Width * xscale2; x++)//b.Height  
            {
                for (int y = bmp.Height / 2; y >= 0; y--)//找到最靠左的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (min_Top > y)
                        {
                            min_Top = y;
                        }
                    }
                }
                for (int y = bmp.Height / 2; y < bmp.Height; y++)//找到最靠右的非黑边位置
                {
                    c = bmp.GetPixel(x, y); //获取该像素点的颜色
                    if (c.R >= color.R + 5 && c.G >= color.G + 5 && c.B >= color.B + 5)//非黑边位置
                    {
                        if (max_Bottom < y)
                        {
                            max_Bottom = y;
                        }

                    }
                }
            }
            //最上：140，最下：986
            //Console.WriteLine($"最上：{min_Top}，最下：{max_Bottom}");
            //创建一个画框：宽
            Bitmap huakuang = new Bitmap(bmp.Width, max_Bottom - min_Top);//986 - 140 =846
            //创建一个画布：宽高和画框一致
            Graphics huabu = Graphics.FromImage(huakuang);
            //清空画布（透明）
            huabu.Clear(System.Drawing.Color.Transparent);
            //画布上所要画的位置和大小
            RectangleF huabu_rec = new RectangleF(0, 0, bmp.Width, max_Bottom - min_Top);
            //图片所要裁剪矩形的大小和位置：
            RectangleF img_rec = new RectangleF(0, min_Top, bmp.Width, max_Bottom - min_Top);
            //在画布上的指定位置大小(huabu_rec)画上图片(bmp)的指定部分(img_rec)
            huabu.DrawImage(bmp, huabu_rec, img_rec, GraphicsUnit.Pixel);
            bmp.Dispose();
            huabu.Dispose();
            return huakuang;
        }
        /// <summary>
        /// bitMap 转 BitMapImage
        /// </summary>
        /// <param name="bitMap"></param>
        /// <returns></returns>
        public static BitmapImage Bitmap2BitMapImage(System.Drawing.Bitmap bitMap)
        {
            MemoryStream ms = new MemoryStream();
            bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            BitmapImage bImage = new BitmapImage();
            bImage.BeginInit();
            bImage.StreamSource = new MemoryStream(ms.ToArray());
            bImage.EndInit();
            bitMap.Dispose();
            ms.Dispose();
            return bImage;
        }

      

        /// <summary>
        /// 裁剪图片
        /// </summary>
        /// <param name="originImage">原图片</param>
        /// <param name="region">裁剪的方形区域</param>
        /// <returns>裁剪后图片</returns>
        public static Bitmap CropImage(Image originImage, Rectangle region)
        {
            System.Drawing.Bitmap result = new Bitmap(region.Width, region.Height);
            Graphics graphics = Graphics.FromImage(result);
            graphics.DrawImage(originImage, new Rectangle(0, 0, region.Width, region.Height), region, GraphicsUnit.Pixel);
            return result;
        }

      
        //二、将字节流转换回图片
        /// <summary>
        /// 根据字节流返回Image类型
        /// </summary>
        /// <param name="streamByte"></param>
        /// <returns></returns>
        public static Image ReturnImage(byte[] streamByte)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
            Image img = Image.FromStream(ms);
            return img;


            //四、保存图片
            //var oldFilename = @"E:\环境部署\图片集\熊猫1.jpg";
            //var oldImage = System.Drawing.Image.FromFile(oldFilename);
            //var newFilename = @"E:\我的新熊猫.jpg";
            //oldImage.Save(newFilename, ImageFormat.Jpeg);

        }

        //三、将Image对象转换为字节流
        //将Image转换成流数据，并保存为byte[]   
        public static byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length); mstream.Close();
            return byData;
        }

        //五、生成缩略图
        /// <summary>
        /// 生成图片缩略文件
        /// </summary>
        /// <param name="originalImage">图片源文件</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        /// <returns>缩率处理后图片文件</returns>
        public static Image MakeThumbnail(Image originalImage, int width, int height, ThumbnailModel mode)
        {
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            switch (mode)
            {
                case ThumbnailModel.HighWidth: //指定高宽缩放（可能变形）
                    break;
                case ThumbnailModel.Width: //指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case ThumbnailModel.Hight: //指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case ThumbnailModel.Default: //指定高，宽按比例
                    if (ow <= towidth && oh <= toheight)
                    {
                        x = -(towidth - ow) / 2;
                        y = -(toheight - oh) / 2;
                        ow = towidth;
                        oh = toheight;
                    }
                    else
                    {
                        if (ow > oh)//宽大于高
                        {
                            x = 0;
                            y = -(ow - oh) / 2;
                            oh = ow;
                        }
                        else//高大于宽
                        {
                            y = 0;
                            x = -(oh - ow) / 2;
                            ow = oh;
                        }
                    }
                    break;
                case ThumbnailModel.Auto:
                    if (originalImage.Width / originalImage.Height >= width / height)
                    {
                        if (originalImage.Width > width)
                        {
                            towidth = width;
                            toheight = (originalImage.Height * width) / originalImage.Width;
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    else
                    {
                        if (originalImage.Height > height)
                        {
                            toheight = height;
                            towidth = (originalImage.Width * height) / originalImage.Height;
                        }
                        else
                        {
                            towidth = originalImage.Width;
                            toheight = originalImage.Height;
                        }
                    }
                    break;
                case ThumbnailModel.Cut: //指定高宽裁减（不变形）
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.White);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);
            return bitmap;
        }

        //其中缩略图模式定义如下：
        /// <summary>
        /// 缩率图处理模式
        /// </summary>
        public enum ThumbnailModel
        {
            /// <summary>
            /// 指定高宽缩放（可能变形）   
            /// </summary>
            HighWidth,

            /// <summary>
            /// 指定宽，高按比例   
            /// </summary>
            Width,

            /// <summary>
            /// 默认  全图不变形   
            /// </summary>
            Default,

            /// <summary>
            /// 指定高，宽按比例
            /// </summary>
            Hight,

            /// <summary>
            /// 指定高宽裁减（不变形）？？指定裁剪区域
            /// </summary>
            Cut,

            /// <summary>
            /// 自动 原始图片按比例缩放
            /// </summary>
            Auto
        }
    }
    //一、将图片转换为字节流
    /// <summary>
    /// 图片处理帮助类
    /// </summary>
    public static class PicProcessHelper
    {
        /// <summary>
        /// 将图片转换为指定的字节流
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <returns>指定的字节流</returns>
        public static byte[] ConvertToByte(String filePath)
        {
            var m = new System.IO.MemoryStream();
            var bp = new System.Drawing.Bitmap(filePath);
            bp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg); //将此图像以指定的格式保存到指定的流中。
            byte[] imgByte = m.GetBuffer(); //从内存缓冲区中读取
            return imgByte;
        }
    }


}
